﻿using System.Collections;
using UnityEngine;

namespace YunHao
{

    public class ResourceLoadControl : MonoBehaviour
    {

        public static ResourceLoadControl Instance
        {
            get
            {
                if (!instance)
                    instance = new GameObject("ResourceLoadControl", typeof(ResourceLoadControl)).GetComponent<ResourceLoadControl>();
                return instance;
            }
        }

        private static ResourceLoadControl instance;

        private void Awake()
        {
            instance = this;
        }

        #region Texture2D Load

        /// <summary>
        /// 加载Texture2D
        /// </summary>
        /// <param name="url"></param>
        /// <param name="onFinish"></param>
        /// <param name="onError"></param>
        public void LoadTexture2D(string url, System.Action<Texture2D> onFinish, System.Action<string> onError)
        {
            StartCoroutine(LoadTexture2DAsync(url, onFinish, onError));
        }

        /// <summary>
        /// 异步加载Texture2D
        /// </summary>
        /// <param name="url"></param>
        /// <param name="onFinish"></param>
        /// <param name="onError"></param>
        /// <returns></returns>
        IEnumerator LoadTexture2DAsync(string url, System.Action<Texture2D> onFinish, System.Action<string> onError)
        {
            using (WWW www = new WWW(url))
            {
                yield return www;
                if (string.IsNullOrEmpty(www.error))
                {
                    if (null != onFinish) onFinish(www.texture);
                }
                else
                {
                    if (null != onError) onError(www.error);
                }
            }
        }

        #endregion

        #region Text Load

        /// <summary>
        /// 加载Text
        /// </summary>
        /// <param name="url"></param>
        /// <param name="onFinish"></param>
        /// <param name="onError"></param>
        public void LoadText(string url, System.Action<string> onFinish, System.Action<string> onError)
        {
            StartCoroutine(LoadTextAsync(url, onFinish, onError));
        }

        /// <summary>
        /// 异步加载Text
        /// </summary>
        /// <param name="url"></param>
        /// <param name="onFinish"></param>
        /// <param name="onError"></param>
        /// <returns></returns>
        IEnumerator LoadTextAsync(string url, System.Action<string> onFinish, System.Action<string> onError)
        {
            using (WWW www = new WWW(url))
            {
                yield return www;
                if (string.IsNullOrEmpty(www.error))
                {
                    if (null != onFinish) onFinish(www.text);
                }
                else
                {
                    if (null != onError) onError(www.error);
                }
            }
        }

        #endregion
    }
}